package net.yegong.gdal;

import java.io.File;
import java.util.Scanner;

public class Gdal {

	public enum Utility {
		GDAL_INFO, GDAL_TRANSLATE
	}

	public static String getGdalPath() {
		return "gdal";
	}

	public static String getGdalUtilityPath(Utility program) {
		switch (program) {
		case GDAL_INFO:
			return getGdalPath() + File.separator + "gdalinfo.exe";
		case GDAL_TRANSLATE:
			return getGdalPath() + File.separator + "gdal_translate.exe";
		default:
			throw new IllegalArgumentException("No such a utility program in gdal package.");
		}
	}

	public static String run(Utility program, String... params) throws Exception {
		return run(getGdalUtilityPath(program), params);
	}

	public static String run(String program, String... params) throws Exception {
		StringBuilder buf = new StringBuilder(program);
		for (String p : params) {
			buf.append(' ');
			buf.append(p);
		}
		Process proc = Runtime.getRuntime().exec(buf.toString());
		buf = new StringBuilder();
		Scanner in = new Scanner(proc.getInputStream());
		Scanner err = new Scanner(proc.getErrorStream());
		while (in.hasNextLine() || err.hasNextLine()) {
			if (in.hasNextLine()) {
				buf.append(in.nextLine());
				buf.append('\n');
			}
			else {
				buf.append(err.nextLine());
				buf.append('\n');
			}
		}
		proc.waitFor();
		return buf.toString();
	}
}
